package com.mobile.common.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;

import javax.imageio.ImageIO;

import org.apache.commons.io.output.ByteArrayOutputStream;
/**
 * @imageStream 返回的图片流
 * @valiCode 图片中对应的字符
 * @author qingqiu
 *
 */
public class AuthenticCode {

	private InputStream imageStream;
	private String valiCode;
	private Random random = new Random();
	private AuthenticCode(){
		ini();
	}
	public static AuthenticCode getInstance(){
		return new AuthenticCode();
	}

	private void ini(){
		int width=60;
		int height=20;
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
		Graphics graphics = image.getGraphics();
		graphics.setColor(new Color(210, 100, 150));
		graphics.fillRect(0, 0, width, height);
		
		graphics.setFont(new Font("Courier New",0,24));
		graphics.setColor(new Color(11,33,44));
		
		for(int j=0;j<20;j++){
			int x1 = random.nextInt(width);
			int y1 = random.nextInt(height);
			int x2 = random.nextInt(x1+10>width?x1:width);
			int y2 = random.nextInt(y1+5>height?y1:height);
			graphics.setColor(getRandomColor());
			graphics.drawLine(x1, y1, x2, y2);
		}
		
		StringBuffer sb = new StringBuffer();
		for(int i=0;i<4;i++){
			String str = String.valueOf(random.nextInt(10));
			sb.append(str);
			graphics.setColor(new Color(12,15,230));
			graphics.drawString(str, 13*i+6, 16);
		}
		valiCode = sb.toString();
		graphics.dispose();
		
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			ImageIO.write(image, "jpeg", ImageIO.createImageOutputStream(output));
			imageStream = new ByteArrayInputStream(output.toByteArray()); 
		} catch (IOException e) {
			e.printStackTrace();
			System.err.println("=====生成图片错误！=========");
		}
	}
	private Color getRandomColor(){
		return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
	}
	//-------------------------------
	
	public String getValiCode() {
		return valiCode;
	}
	public void setValiCode(String valiCode) {
		this.valiCode = valiCode;
	}
	public InputStream getImageStream() {
		return imageStream;
	}
	public void setImageStream(InputStream imageStream) {
		this.imageStream = imageStream;
	}
}
